package com.wb.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.wb.reggie.common.BaseContext;
import com.wb.reggie.common.MyMap;
import com.wb.reggie.common.R;
import com.wb.reggie.entity.Employee;
import com.wb.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 检查用户是否已经完成登录过滤器
 * urlPatterns = "/*"拦截所有请求
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter" ,urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Autowired
    private MyMap myMap;

    //路径匹配器，支持通配符
    public static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    /**
     * 过滤的方法
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //{}占位符
        log.info("拦截到请求：{}",request.getRequestURI());

        //1，获取本次请求的uri
        String requestURI = request.getRequestURI();


        //定义不需要处理的请求路径
        String [] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",//静态资源放行
                "/front/**",
                "/common/**",//静态资源放行
                "/user/sendMsg",//移动端发送短信
                "/user/login", //移动端登录
        };

        //2，判断本次请求是否需要处理，也就是说用匹配器ANT_PATH_MATCHER来判断本次请求是否是以上数组的某一个
        boolean check = check(urls,requestURI);

        //3，如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",request.getRequestURI());
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //4-1，判断登录状态（PC端），如果已登录，直接放行
        Employee employee = (Employee) request.getSession().getAttribute("employee");

        if(employee != null){
            log.info("用户已登录,账号：{}",employee.getUsername());

            Long id = Thread.currentThread().getId();
            log.info("线程id：{}",id);

//            myMap.put(id,employee.getId());
//            log.info("用户id是是：{}",myMap.get(id));

            //设置登录用户的id
            BaseContext.setCurrentId(employee.getId());
            log.info("用户id是是：{}",BaseContext.getCurrentId());

            filterChain.doFilter(request,response);
            return;
        }

        //4-2，判断登录状态（移动端），如果已登录，直接放行
        User user = (User) request.getSession().getAttribute("user");

        if(user != null){
            log.info("用户已登录,账号：{}",user.getName());

            Long id = Thread.currentThread().getId();
            log.info("线程id：{}",id);


            //设置登录用户的id
            BaseContext.setCurrentId(user.getId());
            log.info("用户id是是：{}",BaseContext.getCurrentId());

            filterChain.doFilter(request,response);
            return;
        }

        //5,走到这里说明请求未放行 或 未登录
        //通过输出流的方式将结果写到页面（写的是json数据）
        //另外返回的提示中要与前端契合
        log.info("用户未登录");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(R.error("NOTLOGIN")));

        return;
    }

    /**
     * 检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String [] urls,String requestURI) {
        for (String url : urls) {
            //匹配match()
           boolean match =  ANT_PATH_MATCHER.match(url,requestURI);

           //匹配上了。
           if(match){
               return true;
           }
        }
        return false;
    }
}
